from django.shortcuts import render, redirect, reverse
from django.views.decorators.http import require_POST
from django.http import JsonResponse
from django.core.paginator import Paginator
from django.conf import settings
from django.contrib.auth.decorators import login_required

from xadmin.models import Article, ArticleGroup, Node
from xadmin.forms import ArticleForm
from xadmin.nodeBll import node_tree_list
from xadmin.plugins.auditlog import add_log
from xadmin.nodeBll import GetNodeTree

basic_field = ('parent_node', 'title', 'sub_title', 'order_num', 'hit', 'force_url', 'add_time',
               'is_active', 'picture', 'video', 'file', 'brief')
content_field = ('content',)
ext_field = ('picture2', 'picture3', 'picture4', 'video2', 'video3', 'video4', 'file2', 'file3', 'file4',
             'input1', 'input2', 'input3', 'input4', 'input5',
             'textarea1', 'textarea2', 'textarea3', 'textarea4', 'textarea5')
seo_field = ('seo_title', 'seo_keyword', 'seo_description')


@login_required
def article_list(request):
    mbx = ('内容管理', '文章')
    siteid = request.GET.get('siteid')
    article_list1 = Article.objects.filter(site_id=siteid)
    keyword = request.GET.get('keyword', '')
    nodeid = request.GET.get('nodeid', '0')

    if keyword:
        article_list1 = article_list1.filter(title__contains=keyword)
    if nodeid and nodeid != '0':
        article_list1 = article_list1.filter(parent_node_id=nodeid)
    
    recy = request.GET.get('t')
    
    if recy == 'recy':
        article_list1 = article_list1.filter(is_delete=True)
    else:
        article_list1 = article_list1.filter(is_delete=False)
    

    paginator = Paginator(article_list1, settings.PAGESIZE)

    pagenum = request.GET.get('pagenum', '1')
    if not pagenum.isdigit():
        pagenum = 1
    if int(pagenum) > paginator.num_pages:
        pagenum = paginator.num_pages
    if int(pagenum) < -1:
        pagenum = 1
    article_lists = paginator.get_page(pagenum)

    #文章栏目
    #node_list = Node.objects.filter(node_type='content', is_active=True)
    node_list = GetNodeTree()

    #文章组
    article_groups = ArticleGroup.objects.filter(site_id=siteid)
    context = {
        'article_list': article_lists,
        'siteid': siteid,
        'paginator': paginator,
        'pagesize': settings.PAGESIZE,
        'node_list': node_list,
        'pagenum': pagenum,
        'keyword': keyword,
        'nodeid': int(nodeid),
        'article_groups': article_groups,
        'groupid': 0,
        'mbx': mbx,
        'recy': recy
    }
    return render(request, 'xadmin/article/list.html', context)


@login_required
def article_add(request):
    siteid = request.GET.get('siteid')
    nodeid = request.GET.get('nodeid')
    mbx = ('内容管理', '文章', '添加文章')
    if request.method == 'GET':
        article_form = ArticleForm.ArticleForm()

        context = {
            'siteid': siteid,
            'article_form': article_form,
            'basic_field': basic_field,
            'ext_field': ext_field,
            'content_field': content_field,
            'seo_field': seo_field,
            'mbx': mbx,
            'nodeid': nodeid,
        }
        return render(request, 'xadmin/article/add.html', context)
    else:
        article_form = ArticleForm.ArticleForm(request.POST, request.FILES)
        if article_form.is_valid():
            new_article = article_form.save(commit=False)
            max_ordernum_article = Article.objects.filter().order_by('-order_num').first()
            new_article.order_num = (max_ordernum_article.order_num + 1) if max_ordernum_article else 1
            new_article.site_id = siteid
            new_article.save()
            log_style = '#1ab394'
            action = '添加了文章《%s》' % new_article.title
            add_log(request, action, siteid)

            nodeid = new_article.parent_node_id
            return redirect('%s?siteid=%s&nodeid=%s' % (reverse('articlelist'), siteid, nodeid))
        else:
            error = article_form.errors
            context = {
                'siteid': siteid,
                'article_form': article_form,
                'basic_field': basic_field,
                'ext_field': ext_field,
                'content_field': content_field,
                'seo_field': seo_field,
                'error': error,
                'mbx': mbx
            }
            return render(request, 'xadmin/article/add.html', context)


@login_required
@require_POST
def article_change_state(request):
    mess = {}
    siteid = request.GET.get('siteid', '1')
    try:
        articleid = request.POST.get('id')
        isactive = request.POST.get('isactive')
        article_obj = Article.objects.get(id=articleid)
        article_obj.is_active = True if isactive == '1' else False
        article_obj.save()
        action = '修改了文章《%s》的激活状态' % article_obj.title
        add_log(request, action, siteid)
        mess['status'] = '200'
        mess['message'] = '修改成功'
    except:
        mess['status'] = '500'
        mess['message'] = '修改失败'
    return JsonResponse(mess)


@login_required
@require_POST
def article_del(request):
    mess = {}
    siteid = request.POST.get('siteid', '1')
    try:
        articleid = request.POST.get('articleid')
        article_obj = Article.objects.get(id=articleid)
        article_obj.is_delete = True
        article_obj.save()
        action = '删除了文章《%s》' % article_obj.title
        add_log(request, action, siteid)
        mess['status'] = '200'
        mess['message'] = '删除成功'
    except:
        mess['status'] = '500'
        mess['message'] = '删除失败'
    return JsonResponse(mess)


@login_required
def article_edit(request, articleid):
    siteid = request.GET.get('siteid')
    nodeid = request.GET.get('nodeid')
    pagenum = request.GET.get('pagenum')
    mbx = ('内容管理', '文章', '编辑文章')
    article_obj = Article.objects.get(id=articleid)
    if request.method == 'GET':
        article_form = ArticleForm.ArticleForm(instance=article_obj)
        context = {
            'siteid': siteid,
            'article_form': article_form,
            'basic_field': basic_field,
            'ext_field': ext_field,
            'content_field': content_field,
            'seo_field': seo_field,
            'mbx': mbx,
            'nodeid': nodeid,
            'pagenum': pagenum,
        }
        return render(request, 'xadmin/article/add.html', context)
    else:
        article_form = ArticleForm.ArticleForm(request.POST, request.FILES, instance=article_obj)
        if article_form.is_valid():
            article_form.save()
            action = '修改了文章《%s》' % article_form.cleaned_data['title']
            add_log(request, action ,siteid)
            return redirect('%s?siteid=%s&nodeid=%s&pagenum=%s' % (reverse('articlelist'), siteid, nodeid, pagenum))
        else:
            error = article_form.errors
            context = {
                'siteid': siteid,
                'article_form': article_form,
                'basic_field': basic_field,
                'ext_field': ext_field,
                'content_field': content_field,
                'seo_field': seo_field,
                'mbx': mbx
            }
            return render(request, 'xadmin/article/add.html', context)


@login_required
@require_POST
def articles_del(request):
    ids = request.POST.get('ids')
    siteid = request.POST.get('siteid', '1')
    id_list = ids.split(',')
    mess = {}
    try:
        articles = Article.objects.filter(id__in=id_list)
        articles.update(is_delete=True)
        action = '删除了文章 %s' % ','.join(['《%s》' %  x.title for x in articles])
        add_log(request, action, siteid)
        mess['status'] = '200'
        mess['msg'] = '删除成功'
    except:
        mess['status'] = '500'
        mess['msg'] = '删除失败'
    return JsonResponse(mess)


@login_required
def articles_move(request):
    siteid = request.GET.get('siteid')
    if request.method == 'GET':
        article_node_list = Node.objects.filter(site_id=siteid, is_active=True, node_type='content')
        ids = request.GET.get('ids')
        node_list_str = ''
        node_tree_json = ''
        if(article_node_list):
            for anode in article_node_list:
                node_list_str += anode.node_path + ',' + str(anode.id) + ','

            node_set = set(node_list_str.strip(',').split(','))   #参与展示的栏目

            nodes_list_value = Node.objects.filter(id__in=node_set).values()
            node_tree_json = node_tree_list(nodes_list_value)  #栏目结构的 json数据
        context = {
            'siteid': siteid,
            'node_tree_json': node_tree_json,
            'ids': ids
        }
        return render(request, 'xadmin/node/selectNodeSingle.html', context)
    else:
        nodeid = request.POST.get('nodeid')
        articleids = request.POST.get('articleids')
        articleid_list = []
        mess = {}
        if articleids:
            articleid_list = articleids.split(',')
        try:
            articles = Article.objects.filter(id__in=articleid_list)
            articles.update(parent_node_id=nodeid)
            node = Node.objects.get(id=nodeid)
            action = '转移文章 %s 到 栏目 %s' % (','.join(['《%s》' % x.title for x in articles]), node.name)
            add_log(request, action, siteid)
            mess['status'] = '200'
            mess['msg'] = '转移成功'
        except:
            mess['status'] = '500'
            mess['msg'] = '转移失败'
        return JsonResponse(mess)


@login_required
def articles_copy(request):
    siteid = request.GET.get('siteid')
    if request.method == "GET":
        article_node_list = Node.objects.filter(site_id=siteid, is_active=True, node_type='content')
        ids = request.GET.get('ids')
        node_list_str = ''
        node_tree_json = ''
        if (article_node_list):
            for anode in article_node_list:
                node_list_str += anode.node_path + ',' + str(anode.id) + ','

            node_set = set(node_list_str.strip(',').split(','))
            nodes_list_value = Node.objects.filter(id__in=node_set).values()
            node_tree_json = node_tree_list(nodes_list_value)
        context = {
            'siteid': siteid,
            'node_tree_json': node_tree_json,
            'ids': ids
        }
        return render(request, 'xadmin/node/selectNodeMuti.html', context)
    else:
        nodeids = request.POST.get('nodeids')
        articleids = request.POST.get('articleids')
        mess = {}
        try:
            article_list = Article.objects.filter(id__in=articleids.split(','))
            for article in article_list:
                for n in nodeids.split(','):
                    article.id = None
                    article.parent_node_id = n
                    article.save()
            nodes = Node.objects.filter(id__in=nodeids.split(','))
            action = '复制文章 %s 到栏目 %s ' % (','.join(['《%s》' % x.title for x in article_list]), ','.join(['《%s》' % x.name for x in nodes]))
            add_log(request, action, siteid)
            mess['status'] = '200'
            mess['msg'] = '复制成功'
        except Exception as e:
            mess['status'] = '500'
            mess['msg'] = '复制失败'
        return JsonResponse(mess)


@login_required
@require_POST
def article_add_group(request):
    siteid = request.GET.get('siteid')
    gids = request.POST.get('gids')
    articleid = request.POST.get('articleid')
    mess = {}
    try:
        article_obj = Article.objects.get(id=articleid)
        gid_list = gids.split(',')
        group_list = []
        #先清空该文章的组信息,再添加
        #ArticleGroup.objects.filter(article=article_obj).clear()
        article_obj.article_group.clear()
        for gid in gid_list:
            group_obj = ArticleGroup.objects.get(id=gid)
            group_obj.article.add(article_obj)
            group_list.append(group_obj.name)
        action = '文章《%s》添加到组 [%s]' % (article_obj.title, ','.join(group_list))
        add_log(request, action, siteid)
        mess['status'] = '200'
        mess['msg'] = '添加成功'
    except Exception as e:
        print(e)
        mess['status'] = '500'
        mess['msg'] = '添加失败'
    return JsonResponse(mess)


@login_required
@require_POST
def article_remove_group(request):
    siteid = request.POST.get('siteid')
    articleid = request.POST.get('articleid')
    groupid = request.POST.get('groupid')

    mess = {}
    try:
        group = ArticleGroup.objects.get(id=groupid)
        article = Article.objects.get(id=articleid)
        group.article.remove(article)
        action = '文章《%s》从组 [%s] 中移出' % (article.title, group.name)
        add_log(request, action, siteid)
        mess['status'] = '200'
        mess['msg'] = '文章已从组中移出'
    except Exception as e:
        #print(e)
        mess['status'] = '500'
        mess['msg'] = '移出失败'
    return JsonResponse(mess)


@login_required
def article_filter_group(request):
    groupid = request.GET.get('groupid')
    siteid = request.GET.get('siteid')
    mbx = ('内容管理', '文章')
    #多对多查询
    group = ArticleGroup.objects.get(id=groupid)
    article_list1 = group.article.select_related()

    paginator = Paginator(article_list1, settings.PAGESIZE)

    pagenum = request.GET.get('pagenum', '1')
    if not pagenum.isdigit():
        pagenum = 1
    if int(pagenum) > paginator.num_pages:
        pagenum = paginator.num_pages
    if int(pagenum) < -1:
        pagenum = 1
    article_lists = paginator.get_page(pagenum)

    # 文章栏目
    node_list = Node.objects.filter(node_type='content', is_active=True)

    # 文章组
    article_groups = ArticleGroup.objects.filter(site_id=siteid)
    context = {
        'article_list': article_lists,
        'siteid': siteid,
        'paginator': paginator,
        'pagesize': settings.PAGESIZE,
        'node_list': node_list,
        'pagenum': pagenum,
        'article_groups': article_groups,
        'groupid': group.id,
        'mbx': mbx
    }
    return render(request, 'xadmin/article/list.html', context)
    
    
@login_required
@require_POST
def article_restore(request):
    siteid = request.POST.get('siteid')
    articleid = request.POST.get('articleid')
    article_obj = Article.objects.get(id=articleid)
    article_obj.is_delete = False
    article_obj.save()
    action = '文章《%s》从回收站中还原' % article_obj.title
    add_log(request, action, siteid)
    mess = {}
    # pagenum = request.POST.get('pagenum', '1')
    # keyword = request.POST.get('keyword', '')
    # nodeid = request.POST.get('nodeid', '0')
    # groupid = request.POST.get('groupid', '0')
    # url = reverse('articlelist') + '?siteid=' + siteid + '&t=recy&pagenum=' + pagenum
    # if keyword:
    #     url += '&keyword=' + keyword
    # if nodeid != '0':
    #     url += '&nodeid=' + nodeid
    # if groupid != '0':
    #     url += '&groupid=' + groupid
    mess['status'] = '200'
    mess['msg'] = '文章已还原'


    return JsonResponse(mess)


@login_required
@require_POST
def article_clear(request):
    '''从回收站中删除文章'''
    articleid = request.POST.get('articleid')
    siteid = request.POST.get('siteid')
    article_obj = Article.objects.get(id=articleid)
    article_obj.delete()
    action = '文章《%s》从回收站中删除' % article_obj.title
    add_log(request, action, siteid)
    mess = {}
    mess['status'] = '200'
    mess['msg'] = '文章已彻底删除'

    return JsonResponse(mess)


@login_required
@require_POST
def article_clear_all(request):
    '''清空回收站'''
    siteid = request.POST.get('siteid')
    Article.objects.filter(is_delete=True, site_id=siteid).delete()
    action = '清空了回收站'
    add_log(request, action, siteid)
    mess = {}
    mess['status'] = '200'
    mess['msg'] = '回收站已清空'

    return JsonResponse(mess)




